package cn.dansj.common.mail.utils.javamail;

import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class ConfigurableMimeFileTypeMap extends FileTypeMap {
    private String[] mappings;

    private FileTypeMap fileTypeMap;

    public void setMappings(String... mappings) {
        this.mappings = mappings;
    }

    public void afterPropertiesSet() {
        getFileTypeMap();
    }

    protected final FileTypeMap getFileTypeMap() {
        if (this.fileTypeMap == null) {
            try (InputStream mappingLocation = ConfigurableMimeFileTypeMap.class.getClassLoader().getResourceAsStream("mime.types")) {
                this.fileTypeMap = createFileTypeMap(mappingLocation, this.mappings);
            } catch (IOException ex) {
                throw new IllegalStateException(
                        "Could not load specified MIME type mapping file: mime.types", ex);
            }
        }
        return this.fileTypeMap;
    }

    protected FileTypeMap createFileTypeMap(InputStream mappingLocation, String[] mappings) throws IOException {
        MimetypesFileTypeMap fileTypeMap = mappingLocation != null ? new MimetypesFileTypeMap(mappingLocation) : new MimetypesFileTypeMap();

        if (mappings != null) {
            for (String mapping : mappings) {
                fileTypeMap.addMimeTypes(mapping);
            }
        }
        return fileTypeMap;
    }

    @Override
    public String getContentType(File file) {
        return getFileTypeMap().getContentType(file);
    }

    @Override
    public String getContentType(String fileName) {
        return getFileTypeMap().getContentType(fileName);
    }
}
